var oper = getQueryString('oper')
var roleId = getQueryString('id')
$(function () {
  var url = "/admin/dept/tree";
  var options = {
    id: "deptTrees",
    url: url,
    check: {enable: true, nocheckInherit: false/* , chkboxType: {"Y": "ps", "N": "ps"} */},
    expandLevel: 2,
    onClick : zOnClick,
  };
  $.tree.init(options);


  $('#oper').val(oper)
  if (oper === 'edit' || oper === 'view') {
    roleDetail(roleId)
    $('#roleCode').attr('readonly', true)
  }
  dataScopeVisible('0')

  jQuery.validator.addMethod("format",function(value,element){
    var account = /^[A-Z_]+$/;
    return account.test(value);
  },"请输入大写英文、下划线");

  $.common.initFormInfo();
});

function zOnClick(event, treeId, treeNode) {
	var treeId = treeNode.id;
	var treeName = treeNode.name;
	if (treeNode.children){
		$._tree.checkNode(treeNode)
	}
	$("#treeId").val(treeId);
	$("#treeName").val(treeName);
}

$("#editForm").validate({
  onkeyup: false,
  rules: {
    roleName: {
      required: true
    },
    roleCode: {
      required: true,
      format: true
    },
    dsType: {
      required: true
    }
  },
  messages: {
    roleName: {
      required: "请输入角色名称"
    },
    roleCode: {
      required: "请输入角色编码"
    },
    dsType: {
      required: "请选择数据范围"
    }
  },
  focusCleanup: true
});

$("#dsType").change(function (event) {
  var dataScope = $(event.target).val();
  dataScopeVisible(dataScope);
});

function roleDetail(id) {
  $.operate.get(api + '/admin/role/' + id, function (res) {
    res.data.oper = oper
    applyDrawing('#editForm', res.data)
    if (res.data.dsType == 1 && res.data.dsScope) {
      var deptIds = res.data.dsScope.split(',')
      deptIds.forEach(function (id) {
        var node = $._tree.getNodeByParam("id", id)
        $._tree.checkNode(node)
      })
    }
    dataScopeVisible(res.data.dsType)
    $.common.initFormInfo();
  }, false)
}

function dataScopeVisible(dataScope) {
  if (dataScope == 1) {
    $("#authDataScope").show();
  } else {
    // $._tree.checkAllNodes(false);
    $("#authDataScope").hide();
  }
}

function submitHandler() {
  if ($.validate.form()) {
    var deptIds = $.tree.getCheckedAllCheckNodes();
    $('#dsScope').val(deptIds);
    $.common.ajaxCommitForm($('#editForm'), false);
    return false;
  }
}